﻿#region COPYRIGHT
//--------------------------------------------------------------------------------
// <copyright file="RenderTargetRenderer.cs" company="starLiGHT Entertainment Studios">
//    Copyright (c) 2008, 2009, 2010, 2011
//       Roland Rosenkranz (Glatzemann@email.de)
// </copyright>
// <license>
//   This file is part of starLiGHT.Particles.
//
//   starLiGHT.Particles is free software: you can redistribute it and/or modify
//   it under the terms of the GNU Lesser General Public License as published by
//   the Free Software Foundation, either version 3 of the License, or
//   (at your option) any later version.
//
//   starLiGHT.Particles is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU Lesser General Public License for more details.
//
//   You should have received a copy of the GNU Lesser General Public License
//   along with starLiGHT.Particles. If not, see http://www.gnu.org/licenses/.
//    
//   ADDITIONAL (commercial) LICENSES for starLiGHT.Particles are available on request.
// </license>
// <original_license>
//  * FLINT PARTICLE SYSTEM
//  * .....................
//  * 
//  * Author: Richard Lord
//  * Copyright (c) Richard Lord 2008-2009
//  * http://flintparticles.org
//  * 
//  * 
//  * Licence Agreement
//  * 
//  * Permission is hereby granted, free of charge, to any person obtaining a copy
//  * of this software and associated documentation files (the "Software"), to deal
//  * in the Software without restriction, including without limitation the rights
//  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  * copies of the Software, and to permit persons to whom the Software is
//  * furnished to do so, subject to the following conditions:
//  * 
//  * The above copyright notice and this permission notice shall be included in
//  * all copies or substantial portions of the Software.
//  * 
//  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  * THE SOFTWARE.
// </original_license>
// <version>
// **************[ starLiGHT.Engine SVN ]**********************
// * $Rev::                       $:  Revision of last commit *
// * $Author::                    $:  Author of last commit   *
// * $Date::                      $:  Date of last commit     *
// ************************************************************
// </version>
//--------------------------------------------------------------------------------
#endregion

namespace starLiGHT.ParticleSystem.twoD
{
    #region Using Statements
    using System;
    using System.Collections.Generic;
    using System.Text;
    using starLiGHT.ParticleSystem.Common;
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Graphics;
    using starLiGHT.SceneManagement;

    #endregion

#if !XNA4
    /// <summary>
    /// The RenderTargetRenderer draws particles onto a single RenderTarget. The region of the particle 
    /// system is covered by the RenderTargets dimensions. Particles outside this region are not drawn.
    /// <br />
    /// The texture to be used for each particle is the particle's image property.
    /// <br />
    /// </summary>
    public class RenderTargetRenderer : SpriteRendererBase
    {
        #region Private Members
        private Rectangle canvas;
        private bool smoothing;
        private bool clearBetweenFrames;
        private RenderTarget2D renderTarget;
        private GraphicsDevice graphics;
        private SpriteBatch spriteBatch;
        #endregion

        #region Constructors
        public RenderTargetRenderer(GraphicsDevice graphics) 
            : this(new Rectangle(0, 0, 800, 600), false, graphics) 
        { 
        }

        public RenderTargetRenderer(Rectangle canvas, GraphicsDevice graphics) 
            : this(canvas, false, graphics) 
        { 
        }

        public RenderTargetRenderer(Rectangle canvas, bool smoothing, GraphicsDevice graphics)
            : base()
        {
            this.graphics = graphics;
            this.smoothing = smoothing;
            this.canvas = canvas;
            this.createRenderTarget(this.graphics);
            this.createSpriteBatch(this.graphics);
            this.clearBetweenFrames = true;
        }
        #endregion

        ~RenderTargetRenderer()
        {
            this.graphics = null;
            if (this.spriteBatch != null)
            {
                this.spriteBatch.Dispose();
                this.spriteBatch = null;
            }

            if (this.renderTarget != null)
            {
                this.renderTarget.Dispose();
                this.renderTarget = null;
            }
        }

        protected void createRenderTarget(GraphicsDevice graphics)
        {
            if (this.canvas.IsEmpty)
            {
                return;
            }

            ////if (_texture != null) _texture.Dispose();
            if (this.renderTarget != null)
            {
                this.renderTarget.Dispose();
            }

            this.renderTarget = new RenderTarget2D(graphics, this.canvas.Width, this.canvas.Height, 1, SurfaceFormat.Color);
        }

        protected void createSpriteBatch(GraphicsDevice graphics)
        {
            this.spriteBatch = new SpriteBatch(graphics);
        }

        public bool ClearBetweenFrames
        {
            get { return this.clearBetweenFrames; }
            set { this.clearBetweenFrames = value; }
        }

        public Texture2D Texture
        {
            get { return this.renderTarget.GetTexture(); }
        }

        public override string Type
        {
            get { return RenderTargetRendererFactory.RENDER_TARGET_RENDERER_FACTORY; }
        }

        public override void renderParticles(Particle[] particles)
        {
            this.graphics.SetRenderTarget(0, renderTarget);

            this.graphics.Clear(Color.TransparentBlack);

            this.spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);

#if !ZUNE
            this.graphics.RenderState.AlphaBlendEnable = true;
            this.graphics.RenderState.SourceBlend = Blend.One;
            this.graphics.RenderState.DestinationBlend = Blend.InverseSourceAlpha; 
#endif

            foreach (Emitter2D emitter in Emitters.Values)
            {
                foreach (Particle2D p in emitter.Particles)
                {
                    this.spriteBatch.Draw(p.Texture, 
                                      p.position, 
                                      null, 
                                      p.color, 
                                      p.rotation, 
                                      new Vector2(p.Texture.Width * 0.5f, p.Texture.Height * 0.5f), 
                                      p.scale, 
                                      SpriteEffects.None, 
                                      0.0f);
                }
            }

            this.spriteBatch.End();

            this.graphics.SetRenderTarget(0, null);
        }
    }

    public class RenderTargetRendererFactory : IParticleSystemRendererFactory
    {
        public static string RENDER_TARGET_RENDERER_FACTORY = "RenderTargetRenderer";

        public string Type
        {
            get { return RENDER_TARGET_RENDERER_FACTORY; }
        }

        public IRenderer createInstance(string name, GraphicsDevice graphics)
        {
            return new RenderTargetRenderer(graphics);
        }

        public void destroyInstance(IRenderer renderer)
        {
            ////TODO: renderer.Dispose();
        }
    }
#endif
}
